package com.wzt.lianfirecontrol.fragment.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.home.HomeMessageAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.message.MessageTypeModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.HashMap;
import java.util.LinkedList;

public class HomeMessageFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private SuperSwipeRefreshLayout swipeRefreshLayout;

    private RecyclerView rlv_message_list;
    private LinearLayoutManager linearLayoutManager;
    private HomeMessageAdapter homeMessageAdapter;

    private View include_progress_bar;
    private View include_no_data;
    private View include_no_net;

    private static final int MESSAGE_LIST_REQUEST_WHAT = 0;

    private String currentCompanyId = "";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_message, container, false);
            currentCompanyId = UserInfoModel.getCompandId(activity);
            initView();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipeRefreshLayout = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipeRefreshLayout);
        swipeRefreshLayout.setOnSwipeRefreshListener(this);
        swipeRefreshLayout.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.divider_line_color));

        initMessageList();
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initMessageList() {
        rlv_message_list = itemContentView.findViewById(R.id.rlv_message_list);
        linearLayoutManager = new LinearLayoutManager(activity);
        rlv_message_list.setLayoutManager(linearLayoutManager);
        homeMessageAdapter = new HomeMessageAdapter(activity);
        rlv_message_list.setAdapter(homeMessageAdapter);
    }

    /**
     * 获取首页列表
     */
    private void initHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(ConstData.COMPANYID, UserInfoModel.getCompandId(activity));
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new HomeListHttpHelper(activity, Url.MESSAGE_COUNT_URL, MESSAGE_LIST_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new HomeParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    @Override
    public void onSwipeRefresh() {
        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                updateData();
                swipeRefreshLayout.setRefreshing(false);
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    private class HomeListHttpHelper extends HttpHelper {

        public HomeListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class HomeParseJsonData extends ParseJsonData{

        public HomeParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what){
                case MESSAGE_LIST_REQUEST_WHAT:
                    try {
                        LinkedList<MessageTypeModel> bannerModels = (LinkedList<MessageTypeModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr),
                                MessageTypeModel.class);
                        if (null != bannerModels && bannerModels.size() > 0){
                            bundle.putSerializable("list", bannerModels);
                        }
                        bundle.putBoolean(REQUEST_OK, true);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            include_progress_bar.setVisibility(View.GONE);
            include_no_net.setVisibility(View.GONE);
            include_no_data.setVisibility(View.GONE);
            return;
        }
        switch (msg.what){
            case MESSAGE_LIST_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setListData((LinkedList<MessageTypeModel>)bundle.getSerializable("list"));
                break;
        }
    }

    private void setListData(LinkedList<MessageTypeModel> listData) {
        if (null == listData || listData.size() == 0){
            homeMessageAdapter.clear();
            include_no_data.setVisibility(View.VISIBLE);
            return;
        }
        include_no_data.setVisibility(View.GONE);
        homeMessageAdapter.clear();
        homeMessageAdapter.addDatas(listData);
        homeMessageAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<MessageTypeModel>() {
            @Override
            public void onItemClick(View v, int position, MessageTypeModel data) {
                HashMap<String, String> url_params = new HashMap<>();
                url_params.put("msgTypeId", data.getMsgTypeId());
                url_params.put("title", data.getMsgTypeName());
                Bundle bundle = new Bundle();
                bundle.putString(ConstData.SHOWTYPPE, ConstData.MESSAGELIST);
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.INFOLIST, data.getMsgTypeName(), url_params, bundle);
            }
        });
    }

    @Override
    public void updateData() {
        super.updateData();
        initHttpHelper();
    }

    @Override
    public void onResume() {
        super.onResume();
        initHttpHelper();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden){
            if (!currentCompanyId.equals(UserInfoModel.getCompandId(activity))) {
                updateData();
            }else {
                initHttpHelper();
            }
        }
    }
}
